//评论模块的路由
var express = require("express")
var router = express.Router()
var { checkSession, dateFormat } = require("../utils/index")
var { Mvs, Comment } = require("../utils/model")
router.get("/test", (req, res) => {
    res.send("test-test-comment")
})



router.get("/index", (req, res) => {
    checkSession(req, res, () => {
        var { mid } = req.query
        var obj = {}
        if (mid) {
            obj = { id: mid }
        }
        //封装的函数
        const findOneData = function (obj, callback) {
            Mvs.findOne(obj)
                .then(result => {
                    callback(result)
                })
        }
        //找到数据
        findOneData(obj, (result) => {
            res.render("comment", {
                username: req.session.username,
                result
            })
        })




    })

})
// 提交评论
router.post("/submit", (req, res) => {
    const query = req.query;
    const body = req.body;
    checkSession(req, res, () => {
        Mvs.findOne({
            id: query.mid,
        }).then(movie => {
            body.time = new Date();
            body.author = req.session.username;
            body.mid = query.mid;
            body.movie = movie;
            Comment.insertMany(body)
                .then(result => {
                    //  res.send("评论成功...")
                    res.redirect("/comment/mlist")  //二级路由名称
                })
        })
    })
})


//评论列表
router.get("/mlist", (req, res) => {
    checkSession(req, res, () => {
        // 分页 
        var {
            pageSize,  //前端传过来的数据，
            page     //前端给的页码，当前第几页
        } = req.query;
        var total = 0;
        var totalPage = 0;
        pageSize = pageSize * 1 || 10;   // 每页的数量
        page = page * 1 || 1;   // 页码

        Comment.find({}, {})
            .then(data => {
                total = data.length;  //总数量
                totalPage = Math.ceil(total / pageSize); //总页数
                page = page < 1 ? 1 : page;
                page = page > totalPage ? totalPage : page;

                Comment.find({}, {})
                    .skip((page - 1) * pageSize) //跳过上一页的多少条数据
                    .limit(pageSize)  //限制多少条数据
                    .sort({ _id: -1 })  //排序
                    .then(result => {  //成功回调，渲染
                        result = result.map(item => {
                            item = { ...item._doc, time: dateFormat(item.time) }
                            return item;
                        })
                        res.render('mlist', {
                            username: req.session.username,
                            result,
                            total,  //这后面的数据是为了分页动态化
                            page,
                            pageSize,
                            totalPage
                        })
                    })
            })
    })

})
//当前电影的所有评论
router.get("/moviepin", (req, res) => {
    checkSession(req, res, () => {
        var { mid } = req.query//得到电影的所有评论id
        Comment.find({
            mid
        }, {})
            .sort({ _id: -1 })
            .then(result => {
                result = result.map(item => {
                    item = { ...item._doc, time: dateFormat(item.time) }
                    return item;
                })
                res.render("moviepin", {
                    result,
                    movie: result[0].movie,
                    username: req.session.username
                })
            })
    })
})

//XX的所有电影评论
router.get("/my", (req, res) => {
    checkSession(req, res, () => {
        const { author } = req.query
        Comment.find({
            author
        })
            .sort({ _id: -1 })
            .then(result => {
                result = result.map(item => {
                    item = { ...item._doc, time: dateFormat(item.time) }
                    return item;
                })
                res.render("my", {
                    result,
                    author,
                    username: req.session.username
                })
            })
    })
})

//评论详情
router.get("/detail", (req, res) => {
    checkSession(req, res, () => {
        const { _id } = req.query;
        Comment.findOne({
            _id
        })
            .then(result => {
                result = { ...result._doc, time: dateFormat(result.time) }
                res.render("detail", {
                    result,
                    username: req.session.username
                })
            })
    })

})

//回复子评论
router.post("/answersubmit", (req, res) => {
    checkSession(req, res, () => {
        var {
            _id,
            subtitle
        } = req.body
        Comment.findOne({
            _id
        })
            .then(data => {
                var answer = data.answer || []
                console.log(answer)
                answer.push({
                    subtitle,
                    id: answer.length,   //自增id
                    author: req.session.username,
                    time: dateFormat(new Date())
                })
                Comment.updateMany({
                    _id
                }, {
                    $set: {
                        answer
                    }
                }).then(result => {   //操作到这里重定向页面
                    res.json({   //用ajax一定要用res.json写法
                        code: 200,
                        msg: "回复评论成功",
                        result,
                        type: 1
                    })
                })
            })
    })
})

//删除评论操作  注：用ajax就要用到res.json来操作
router.post("/delsubmit", (req, res) => {
    checkSession(req, res, () => {
        var { _id } = req.body
        Comment.remove({
            _id
        }).then(result => {
            res.json({
                code: 200,
                msg: "删除评论成功",
                result,
                type: 1

            })
        })
    })
})

//修改评论
router.get("/update", (req, res) => {
    checkSession(req, res, () => {
        var {
            _id
        } = req.query;
        Comment.findOne({
            _id
        }).then(result => {
            result = { ...result._doc, time: dateFormat(result.time) }
            res.render("update", {
                result,
                movie: result.movie,
                username: req.session.username
            })
        })
    })
})
//修改评论
router.post("/updatesubmit", (req, res) => {
    checkSession(req, res, () => {
        var body = req.body
        body.time = new Date()
        Comment.updateMany({
            _id: req.query._id
        }, {
            $set: body
        }).then(result => {
            res.redirect("/comment/mlist")
        }).catch(err => {

        })
    })
})

var multiparty = require("multiparty")
var fs = require("fs")
// 上传图片
router.post("/uploadImg",(req,res)=>{
    const form = new multiparty.Form();
    form.encoding = "utf-8"
    form.uploadDir = "./uploadtemp"  // 临时文件中转站
    form.maxFilesSize = 8*1024*1024;  // 2M 
    form.parse(req,function(err,fields,files){
        if(err) {
            console.log(err)
            res.send("<script>alert('图片过大,请重新上传');location.reload()'</script>")
        }
        var uploadUrl = "/images/upload/",
        file  = files['filedata'], // 图片信息
        originalFilename = file[0].originalFilename, // 文件名
        tempath = file[0].path;
        var timestamp = new Date().getTime(); // 时间戳
        uploadUrl += timestamp+originalFilename;  // 1.jpg ==> 15112341231.jpg
        var newPath = "./public"+uploadUrl;  // 最后路径 
        var fileRead = fs.createReadStream(tempath);
        var fileWrite = fs.createWriteStream(newPath);
        fileRead.pipe(fileWrite);
        fileWrite.on("close",()=>{
            fs.unlinkSync(tempath);
            res.json({
                err:"",
                msg:uploadUrl
            })
        })
    })
})

module.exports = router
